package team3.tracking.communication;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPServerHandler {
	private DatagramSocket serverSocket = null;
	private int port;
	private UDPServerAdapter callingClass;
	private ThreadPool threadPool;
	private Thread thread;
	private final int dataSize = 256;
	private boolean usingThreadPool;
	
	public UDPServerHandler(UDPServerAdapter callingClass, ThreadPool threadPool, int port){ 
																			//will use the threadPool
										//this is the constructor we are using for this app
		this.callingClass = callingClass; //the class that called this UDPServerHandler (must implement UDPServerAdapter)
		this.threadPool = threadPool;
		this.port = port;
		usingThreadPool = true;
	}
	
	public UDPServerHandler(UDPServerAdapter callingClass, int port){ //will create a new independent thread
		this.callingClass = callingClass;
		this.port = port;
		usingThreadPool = false;
	}
	
	public void start(){ //connect and use the threadPool to receive a packet
		try {
    		serverSocket = new DatagramSocket(port);
    	} catch (SocketException e) {
    		e.printStackTrace();
    	}  
		if(usingThreadPool)
			threadPool.execute(new ReceiveUDPPacket());
		else{
			thread = new Thread(new ReceiveUDPPacket());
			thread.start();
		}
	}
	
	public void close(){ //close the socket
		if(serverSocket != null){
			serverSocket.close();
			serverSocket = null;
		}
	}
	public class ReceiveUDPPacket implements Runnable{
		
		public void run(){
			// allocate space for received datagram
			byte[] data = new byte[dataSize];
			DatagramPacket packet = new DatagramPacket(data, data.length);

			while (serverSocket!=null){ 
				//receive one datagram
				try {					
						serverSocket.receive(packet);
						//do something with what was read
						callingClass.onUDPDataReceived(packet.getData(), packet.getLength());
				} catch (IOException e) { //when socket is closed, it will throw this exception,
										  //allowing it to leave the "while" and close the thread.					
					//e.printStackTrace();
				}							
			}
			
		}
	}
	
}
